<?php
/**
 * CopyBase.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2020/12/16- 上午11:17
 */

namespace common\jobs\copy;


use common\constants\CopyConst;
use common\jobs\models\PddCopyProducts;
use console\components\helpers\ConsoleHelper;
use common\models\es\EsCopyProducts;
use Yii;
use yii\helpers\FileHelper;

class CopyBase
{
    /**
     * 批次信息
     * @var \api\models\PddCopyLogs|null
     */
    public $batchInfo = null;


    /**
     * @var PddCopyProducts
     */
    public $logInfo = null;


    /**
     * 导入日志
     * @var \common\components\misc\ImportLogger
     */
    public $logger;


    /**
     * 总数缓存前缀
     * @var string
     */
    public $totalCacheKey = 'copy:total:';


    /**
     * 成功数量
     * @var string
     */
    public $cacheSuccessKey = 'copy:success:';


    /**
     * 失败数量
     * @var string
     */
    public $cacheErrorKey = 'copy:error:';
    /**
     * 成功次数
     */
    protected function setSuccessNum()
    {
        $cacheSuccessNum = Yii::$app->redis->get($this->cacheSuccessKey);
        if(!$cacheSuccessNum)
        {
            Yii::$app->redis->setex($this->cacheSuccessKey,86400,1);
        }else{
            Yii::$app->redis->incr($this->cacheSuccessKey);
        }
        $this->upsetBatchInfo();
    }

    protected function getSuccessNum()
    {
        return  Yii::$app->redis->get($this->cacheSuccessKey);
    }


    /**
     * 失败次数
     */
    protected function setErrorNum()
    {
        $cacheErrorNum = Yii::$app->redis->get($this->cacheErrorKey);
        if(!$cacheErrorNum)
        {
            Yii::$app->redis->setex($this->cacheErrorKey,86400,1);
        }else{
            Yii::$app->redis->incr($this->cacheErrorKey);
        }
        $this->upsetBatchInfo();
    }
    protected function getErrorNum()
    {
        return  Yii::$app->redis->get($this->cacheErrorKey);
    }
    protected function upsetBatchInfo()
    {
        $successNum = (int)$this->getSuccessNum();
        $errorNum = (int)$this->getErrorNum();
        $totalNum = $successNum + $errorNum;

        /**
         * 每10次更新下批次号中的成功和失败数量
         */
        if($totalNum%10 == 0 && $totalNum != $this->batchInfo->total_cnt)
        {
            $this->batchInfo->success_cnt = $successNum;
            $this->batchInfo->fail_cnt = $errorNum;
            $this->batchInfo->save();
        }
        if($totalNum == $this->batchInfo->total_cnt)
        {
            $this->batchInfo->success_cnt = $successNum;
            $this->batchInfo->fail_cnt = $errorNum;
            $this->batchInfo->status = CopyConst::COPY_BATCH_OVER;
            $this->batchInfo->save();
            Yii::$app->redis->del($this->cacheErrorKey);
            Yii::$app->redis->del($this->cacheSuccessKey);
            Yii::$app->redis->del($this->totalCacheKey);
        }
    }


    /**
     * @param string $msg
     * @throws \yii\base\Exception
     */
    protected function writeMappingError(string $msg)
    {
        $path = Yii::getAlias('@runtime/job/errorMapping/');
        //目录如果不存就先创建目录
        if(!is_dir($path)) {
            FileHelper::createDirectory($path);
        }
        $cp = fopen($path.'error-'.date('Ymd').'.log', "a+");
        $txt = "【".date('Y-m-d H:i:s',time())."】---".$msg."\r\n";
        fwrite($cp, $txt);
        fclose($cp);

    }
    
    /**
     * 回写日志记录状态
     * @param array $data
     */
    protected function saveLog(array $data)
    {
        $this->logInfo->status = $data['status'];
        //$this->logInfo->product_status = $data['product_status'];
        $this->logInfo->updated_at =time();
        $result = $this->logInfo->save();
//        $info = $this->logInfo->toArray();
//        if($info){
//            if(isset($info['id'])){
//                $idsArr[] = $info['id'];
//                $es = new EsCopyProducts();
//                unset($info['id']);
//                $es->updateByfield($idsArr,$info);
//            }
//        }
        if(!$result)
        {
            ConsoleHelper::runInfo($this->logInfo->errorsToOneString());
        }
    }
}